package com.cdu.guoxinan.www.smartcom.controller;

import com.cdu.guoxinan.www.smartcom.aop.Annotation.OperationLog;
import com.cdu.guoxinan.www.smartcom.domian.dto.*;
import com.cdu.guoxinan.www.smartcom.domian.pojo.User;
import com.cdu.guoxinan.www.smartcom.domian.vo.LoginVO;
import com.cdu.guoxinan.www.smartcom.service.UserService;
import com.cdu.guoxinan.www.smartcom.unit.model.R;
import com.cdu.guoxinan.www.smartcom.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jetbrains.annotations.NotNull;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.cdu.guoxinan.www.smartcom.util.EmailTool;

import javax.annotation.Resource;

import io.swagger.annotations.ApiModelProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {
    @Resource
    private UserService userService;
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public R login(@Validated LoginDTO loginDto){
        User user = userService.login(loginDto);
        if (user == null) {
            return R.error("登录信息错误");
        }

        LoginVO loginVO = userService.getLoginVO(user);
        return R.ok(loginVO);
    }
    @GetMapping("/query")
    @ApiModelProperty("返回所有用户")
    public R queryAll( QueryUserDTO queryUserDTO) {
        return userService.query(queryUserDTO);
    }
    @PostMapping("/update")
    @ApiModelProperty("更新用户信息")
    @OperationLog(description = "更新用户信息")
    public R updata( UpdataUserDTO updataUserDTO) {
        return userService.updata(updataUserDTO)?R.ok("更新成功"):R.error("更新失败");
    }
    @PostMapping("/add")
    @ApiOperation("添加用户")
    @OperationLog(description = "添加用户")
    public R add(User user) {
        return userService.add(user)?R.ok("添加成功"):R.error("添加失败");
    }
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public @NotNull R register(@Validated registerDTO registerDTO){
        return userService.register(registerDTO)?R.ok("注册成功"):R.error( "注册失败");
    }
    @PostMapping("/reset-password")
    @ApiOperation("重置密码")
    public R resetPassword(@Validated ResetDTO resetDTO, @RequestParam String code) {
        String email = resetDTO.getEmail();

        // 校验验证码
        if (!EmailTool.verifyCode(email, code)) {
            return R.error("验证码错误或已过期");
        }

        boolean success = userService.resetPassword(resetDTO);
        if (success) {
            EmailTool.clearCode(email); // 清除验证码
            return R.ok("重置密码成功");
        } else {
            return R.error("重置密码失败");
        }
    }
    @PostMapping("/change-password")
    @ApiOperation("修改密码（通过旧密码）")
    public R changePassword(@Validated @RequestBody ChangePasswordDTO dto) {
        boolean success = userService.changePassword(dto);
        if (success) {
            return R.ok("密码修改成功");
        } else {
            return R.error("原密码错误或修改失败");
        }
    }

    @PostMapping("/queryByEmail")
    @ApiOperation("通过邮箱查询用户")
    public R queryByeMail(String email){
        User user = userService.queryByeMail(email);
        return user==null?R.error("用户不存在"):R.ok(user);
    }
    @PostMapping("/queryByUsername")
    @ApiOperation("通过用户名查询用户")
    public R queryByUsername(String username){
        User user = userService.queryByUsername(username);
        return user==null?R.error("用户不存在"):R.ok(user);
    }
    @PostMapping("/sendCode")
    @ApiOperation("发送邮箱验证码")
    public R sendVerificationCode(@RequestParam String email) {
        if (!EmailTool.isValidEmail(email)) {
            return R.error("请输入有效的邮箱地址");
        }

        boolean success = EmailTool.sendVerificationCode(email);
        if (success) {
            return R.ok("验证码已发送，请查收邮箱");
        } else {
            return R.error("邮件发送失败，请稍后再试");
        }
    }
    @PostMapping("/getUserId")
    @ApiOperation("获取用户ID")
    public R getUserId(String username){
        Integer userId = userService.getUserId(username);
        return userId==null?R.error("用户不存在"):R.ok(userId);
    }
    @PostMapping("/profile")
    @ApiOperation("获取用户资料")
    public R getUserProfile(@RequestBody Map<String, Object> payload) {
        Long userId = ((Number) payload.get("userId")).longValue();

        UserProfileDTO user = userService.getUserProfileById(userId);

        if (user == null) {
            return R.error("用户不存在");
        }

        return R.ok(user);
    }
    @PostMapping("/changeProfile")
    @ApiOperation("获取用户资料")
     public R updateUserProfile(@RequestBody UserProfileDTO updataUserDTO) {
        boolean success = userService.changeProfile(updataUserDTO);
        if (success) {
            return R.ok("更新成功");
        } else {
            return R.error("更新失败");
        }
    }
}